package com.probox.common.entity.service.customer.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.constant.Constants;
import com.probox.common.core.enums.CustomerLevelPatternTypeEnum;
import com.probox.common.core.enums.CustomerLevelStartTypeEnum;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.customer.CustomerFund;
import com.probox.common.entity.domain.customer.CustomerLevelInfo;
import com.probox.common.entity.domain.customer.PaymentRule;
import com.probox.common.entity.mapper.customer.*;
import com.probox.common.entity.service.customer.ICustomerLevelInfoService;
import com.probox.common.entity.service.customer.ICustomerLevelService;
import com.probox.common.entity.vo.customer.CustomerLevelInfoVo;
import com.probox.common.redis.service.RedisService;
import com.probox.customer.api.domain.CustomerInfoAccount;
import com.probox.customer.api.domain.CustomerLevel;
import com.probox.customer.api.domain.CustomerLevelOpenVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 客户信息、等级关系映射Service业务层处理
 *
 * @author zsy
 * @date 2021-05-27
 */
@Service
@Transactional
public class CustomerLevelInfoServiceImpl extends ServiceImpl<CustomerLevelInfoMapper, CustomerLevelInfo> implements ICustomerLevelInfoService {
    @Autowired
    private CustomerLevelInfoMapper customerLevelInfoMapper;

    @Autowired
    private CustomerFundMapper customerFundMapper;

    @Autowired
    private CustomerLevelMapper customerLevelMapper;

    @Autowired
    private ICustomerLevelService customerLevelService;

    @Autowired
    private PaymentRuleMapper paymentRuleMapper;

    @Autowired
    private CustomerInfoAccountMapper customerInfoAccountMapper;

    @Autowired
    public RedisService redisService;


    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static String customerInfoKey = CachePrefix.CUSTOMER_INFO_DETAIL;

    private static String customerBindLevelKey = CachePrefix.CUSTOMER_BIND_LEVEL;

    //获取客户绑定等级信息过期时间
    private Long expires = 1L;

    /**
     * 根据客户id查询等级名称
     *
     * @param customerUid
     * @return
     */
    @Override
    public String getLevelNameByUid(Long customerUid) {
        return customerLevelInfoMapper.getLevelNameByUid(customerUid);
    }


    @Override
    public CustomerLevel getLevelByUid(Long customerUid) {
        return customerLevelInfoMapper.getLevelByUid(customerUid);

    }

    /**
     * 查询客户信息、等级关系映射
     *
     * @param customerUid 客户信息、等级关系映射ID
     * @return 客户信息、等级关系映射
     */
    @Override
    public CustomerLevelInfo selectCustomerLevelInfoById(Long customerUid) {
        QueryWrapper<CustomerLevelInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("CUSTOMER_UID", customerUid);
        queryWrapper.orderByDesc("LEVEL_INFO_ID").last("limit 1");
        return customerLevelInfoMapper.selectOne(queryWrapper);
    }


    /**
     * 查询客户信息、等级关系映射列表
     *
     * @param customerLevelInfo 客户信息、等级关系映射
     * @return 客户信息、等级关系映射
     */
    @Override
    public List<CustomerLevelInfo> queryList(CustomerLevelInfo customerLevelInfo) {
        QueryWrapper<CustomerLevelInfo> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(customerLevelInfo.getCustomerUid())) && customerLevelInfo.getCustomerUid() != null) {
            queryWrapper.eq("CUSTOMER_UID", customerLevelInfo.getCustomerUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerLevelInfo.getLevelUid())) && customerLevelInfo.getLevelUid() != null) {
            queryWrapper.eq("LEVEL_UID", customerLevelInfo.getLevelUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerLevelInfo.getExpireTime())) && customerLevelInfo.getExpireTime() != null) {
            queryWrapper.eq("EXPIRE_TIME", customerLevelInfo.getExpireTime());
        }
        return customerLevelInfoMapper.selectList(queryWrapper);
    }


    /**
     * 绑定等级信息
     *
     * @param fundUId
     */
    @Override
    public void bindCustoemrLevelProbox(Long fundUId, Long platformUid) {

        logger.info(fundUId + "开始查询绑定客户等级");
        CustomerFund customerFund = customerFundMapper.selectById(fundUId);
        if (customerFund != null) {
            //免费等级
            QueryWrapper<CustomerLevel> levelQueryWrapper = new QueryWrapper<>();
            levelQueryWrapper.eq("PLATFORM_ID", platformUid);
            levelQueryWrapper.le("MIN_SCORE", customerFund.getAllProfit());
            levelQueryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
            levelQueryWrapper.eq("START_STATUS", CustomerLevelStartTypeEnum.start.getKey());
            //levelQueryWrapper.eq("CUSTOMER_PATTERN", CustomerLevelPatternTypeEnum.freeMode.getKey());
            levelQueryWrapper.orderByDesc("CUSTOMER_GRADE").last("limit 1");
            CustomerLevel customerLevel = customerLevelMapper.selectOne(levelQueryWrapper);
            //判断当前客户是否绑定等级
            QueryWrapper<CustomerLevelInfo> levelInfoQueryWrapper = new QueryWrapper<>();
            levelInfoQueryWrapper.eq("CUSTOMER_UID", customerFund.getCustomerUid());
            levelInfoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
            levelInfoQueryWrapper.last("order by LEVEL_INFO_ID desc limit 1");
            CustomerLevelInfo levelInfo = customerLevelInfoMapper.selectOne(levelInfoQueryWrapper);
            if (customerLevel != null) {
                if (levelInfo == null || levelInfo.getLevelUid().longValue() != customerLevel.getLevelId()) {
                    /**
                     * 补齐会员级别之间的差距，收获低级别的权益
                     */
                    QueryWrapper<CustomerLevel> levelWrapper = new QueryWrapper<>();
                    levelWrapper.eq("PLATFORM_ID", platformUid);
                    levelWrapper.le("CUSTOMER_GRADE", customerLevel.getCustomerGrade());
                    levelWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
                    levelWrapper.eq("START_STATUS", CustomerLevelStartTypeEnum.start.getKey());
                    levelWrapper.last(" and LEVEL_ID not in (SELECT LEVEL_UID from customer_level_info where CUSTOMER_UID="+customerFund.getCustomerUid()+" and STATUS='1' )");
                    List<CustomerLevel> levels = customerLevelMapper.selectList(levelWrapper);
                    if (levels.size()>0){
                        for(CustomerLevel level:levels){
                            levelInfo = new CustomerLevelInfo();
                            levelInfo.setLevelUid(level.getLevelId());
                            levelInfo.setCustomerUid(customerFund.getCustomerUid());
                            levelInfo.setStatus(DataStatus.valid.getKey());
                            levelInfo.setCustomeRgrade(level.getCustomerGrade().longValue());
                            levelInfo.setCreateTime(new Date());
                            levelInfo.setScore(customerFund.getAllProfit());
                            save(levelInfo);
                            customerLevelService.giveLevelUpgradeGiftBag(levelInfo.getCustomerUid(), platformUid, levelInfo.getLevelUid());
                        }
                    }

                    levelInfo = new CustomerLevelInfo();
                    levelInfo.setLevelUid(customerLevel.getLevelId());
                    levelInfo.setCustomerUid(customerFund.getCustomerUid());
                    levelInfo.setStatus(DataStatus.valid.getKey());
                    levelInfo.setCustomeRgrade(customerLevel.getCustomerGrade().longValue());
                    levelInfo.setCreateTime(new Date());
                    levelInfo.setScore(customerFund.getAllProfit());
                    save(levelInfo);
                    customerLevelService.giveLevelUpgradeGiftBag(levelInfo.getCustomerUid(), platformUid, levelInfo.getLevelUid());

                }
            }
            redisService.deleteObject(customerInfoKey + customerFund.getCustomerUid());
            //删除客户绑定等级缓存
            redisService.deleteObject(customerBindLevelKey + customerFund.getCustomerUid());
        }
        //删除客户基本信息缓存


    }


    @Override
    public Boolean getIsPayLevel(Long customerUid) {
        QueryWrapper<CustomerLevelInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_UID", customerUid);
        queryWrapper.eq("STATUS", DataStatus.valid.getKey());
        List<CustomerLevelInfo> customerLevelInfoList = customerLevelInfoMapper.selectList(queryWrapper);
        if (customerLevelInfoList != null) {
            for (CustomerLevelInfo levelInfo : customerLevelInfoList) {
                CustomerLevel customerLevel = customerLevelMapper.selectById(levelInfo.getLevelUid());
                if (customerLevel != null) {
                    if (CustomerLevelPatternTypeEnum.payMode.getKey().equals(customerLevel.getCustomerPattern())) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }
        return false;
    }



    /**
     * 根据客户查询等级
     *
     * @param customerUid
     * @return
     */
    @Override
    public CustomerLevelInfo getLevel(Long customerUid) {
        return customerLevelInfoMapper.getLevel(customerUid);
    }

    /**
     * 查看客户绑定等级历史记录
     *
     * @param CustomerUid
     * @return
     */
    @Override
    public List<CustomerLevelInfoVo> levelInfoHistory(Long CustomerUid) {
        List<CustomerLevelInfoVo> customerLevelInfoVoList = new ArrayList<>();
        QueryWrapper<CustomerLevelInfo> levelInfoQueryWrapper = new QueryWrapper<>();
        levelInfoQueryWrapper.eq("CUSTOMER_UID", CustomerUid);
        levelInfoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
        levelInfoQueryWrapper.orderByDesc("CREATE_TIME");
        List<CustomerLevelInfo> customerLevelInfoList = customerLevelInfoMapper.selectList(levelInfoQueryWrapper);
        for (CustomerLevelInfo levelInfo : customerLevelInfoList) {
            CustomerLevelInfoVo customerLevelInfoVo = new CustomerLevelInfoVo();
            CustomerLevel customerLevel = customerLevelMapper.selectById(levelInfo.getLevelUid());
            customerLevelInfoVo.setCustomerUid(levelInfo.getCustomerUid());
            customerLevelInfoVo.setLevelName(customerLevel.getLevelName());
            customerLevelInfoVo.setCreateTime(levelInfo.getCreateTime());
            customerLevelInfoVo.setCustomerPattern(customerLevel.getCustomerPattern());
            customerLevelInfoVo.setScore(levelInfo.getScore());
            customerLevelInfoVoList.add(customerLevelInfoVo);
        }
        return customerLevelInfoVoList;
    }

    /**
     * 查看客户绑定等级历史记录总数
     *
     * @param customerUid
     * @return
     */
    @Override
    public Integer levelInfoHistoryTotal(Long customerUid) {
        QueryWrapper<CustomerLevelInfo> levelInfoQueryWrapper = new QueryWrapper<>();
        levelInfoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
        levelInfoQueryWrapper.eq("CUSTOMER_UID", customerUid);
        Integer customerLevelInfoListCount = customerLevelInfoMapper.selectCount(levelInfoQueryWrapper);
        return customerLevelInfoListCount;
    }

    /**
     * 查看客户账号信息
     *
     * @param customerUid
     * @return
     */
    @Override
    public List<CustomerInfoAccount> getCustomerAccount(Long customerUid) {
        QueryWrapper<CustomerInfoAccount> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("CUSTOMER_UID", customerUid);
        accountQueryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        List<CustomerInfoAccount> customerInfoAccountList = customerInfoAccountMapper.selectList(accountQueryWrapper);
        return customerInfoAccountList;
    }

    //获取客户等级信息
    public List<CustomerLevelInfo> getCustomerBindLevelInfo(Long customerUid, Long fundUId, Long platformUid) {
        //更新客户等级
        if (platformUid == null) {
            platformUid = Constants.DEFAULT_PLATFORM_ID;
        }
        String customerBindLevelKey = CachePrefix.CUSTOMER_BIND_LEVEL + customerUid;
        List<CustomerLevelInfo> customerLevelInfoList = redisService.getCacheList(customerBindLevelKey);
        if (ObjectUtil.isEmpty(customerLevelInfoList)) {
            bindCustoemrLevelProbox(fundUId, platformUid);
            QueryWrapper<CustomerLevelInfo> levelInfoQueryWrapper = new QueryWrapper<>();
            levelInfoQueryWrapper.eq("CUSTOMER_UID", customerUid);
            levelInfoQueryWrapper.eq("STATUS", "1");
            levelInfoQueryWrapper.last("order by LEVEL_INFO_ID desc limit 1 ");
            customerLevelInfoList = customerLevelInfoMapper.selectList(levelInfoQueryWrapper);
            if (customerLevelInfoList.size() > 0) {
                redisService.setCacheList(customerBindLevelKey, customerLevelInfoList);
                //redisService.expire(customerBindLevelKey, RedisService.ThirtySecond, TimeUnit.SECONDS);
            }
        }
        return customerLevelInfoList;
    }
}
